from django.shortcuts import redirect
from django.urls import resolve, reverse
from django.contrib import messages
from django.http import HttpResponseForbidden
from django.conf import settings
from .models import Permission


class PermissionMiddleware:
    """
    权限控制中间件
    """
    
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 获取当前请求的URL信息
        try:
            resolved_match = resolve(request.path_info)
            url_name = resolved_match.url_name
            namespace = resolved_match.namespaces
            
            # 构造完整的URL名称
            if namespace and isinstance(namespace, (list, tuple)):
                full_url_name = ':'.join(namespace) + ':' + url_name
            else:
                full_url_name = url_name
                
            # 排除不需要权限检查的路径
            exempt_urls = [
                'accounts:login',
                'accounts:login_without_nav',
                'accounts:register',
                'admin:index',
            ]
            
            # 如果是管理员路径，使用Django自带的权限控制
            if request.path.startswith('/admin/'):
                response = self.get_response(request)
                return response
                
            # 检查用户是否已经登录
            if not request.user.is_authenticated and full_url_name not in exempt_urls:
                # 未登录用户尝试访问受保护的页面，重定向到登录页面
                login_url = getattr(settings, 'LOGIN_URL', '/accounts/login/')
                return redirect('{}?next={}'.format(login_url, request.path))
                
            # 如果用户已登录且访问的URL需要权限检查
            if request.user.is_authenticated and full_url_name not in exempt_urls:
                # 超级用户拥有所有权限
                if request.user.is_superuser:
                    response = self.get_response(request)
                    return response
                
                # 检查用户是否有对应权限
                if not self.check_user_permission(request.user, full_url_name):
                    # 如果没有权限，返回403页面或重定向到首页
                    return HttpResponseForbidden("您没有权限访问此页面")
        
        except Exception as e:
            # 如果解析URL出错，继续处理请求
            pass
            
        response = self.get_response(request)
        return response
    
    def check_user_permission(self, user, url_name):
        """
        检查用户是否有指定URL的权限
        """
        # 对于欢迎页面，所有登录用户都应该有访问权限
        if url_name == 'accounts:welcome':
            return True
            
        # 获取用户所有权限URL名称
        user_permissions = user.get_user_permissions()
        
        # 检查用户是否有对应权限
        return url_name in user_permissions